import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Layout from '../views/layout/index.vue'
import Login from '../views/login/index.vue'
import store from '@/store'
import { getMenuList } from '@/api/common'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'login',
    component: Login
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 不需要权限的页面
const noPromissionRoutes = ['/login', '/404']
interface menuItem {
  path: string
  name: string
  meta: { icon: string }
  component?: () => any
  children: null | menuItem[]
}

router.beforeEach((to, from, next) => {
  if (noPromissionRoutes.includes(to.path)) {
    next()
  } else {
    if (store.state.baseInfo.userInfo) {
      if (store.state.baseInfo.menuList.length === 0) {
        getMenuList().then(({ data: menuList }) => {
          store.commit('baseInfo/setMenuList', menuList)
          menuList.forEach((item: menuItem) => dgloop(item))
          router.addRoute({
            path: '/',
            name: 'layout',
            component: Layout,
            redirect: 'workbench',
            children: menuList
          })
          router.replace(to.fullPath)
        })
      }
      store.commit('func/addTags', to.path)
      next()
    } else {
      next('/login')
    }
  }
})

function dgloop (obj: menuItem) {
  if (obj.children) {
    obj.children.forEach((item: menuItem) => dgloop(item))
  }
  obj.component = () => import('@/views' + obj.path + '/index')
}

export default router
